package by.grsu.coctails.common.handler;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import by.grsu.coctails.common.utils.ImageManager;

import com.google.android.imageloader.BitmapContentHandler;

public class ImageContentHandler extends BitmapContentHandler {

	private Context mContext;

	private AssetManager mAssetManager;

	public ImageContentHandler(Context context) {
		this.mContext = context;
		mAssetManager = mContext.getAssets();
	}

	@Override
	public Bitmap getContent(URLConnection connection) throws IOException {

		String url = connection.getURL().toString()
				.substring(ImageManager.HTTP.length());
		String imageName = ImageManager.getFileNameFromUrl(url);

		String cacheFilePath = mContext.getCacheDir().getAbsolutePath();

		Bitmap result = null;

		if (ImageManager.isOnlineFile(url)) {

			Uri uri = null;

			uri = Uri.parse(url);

			if (!ImageManager.fileExists(cacheFilePath + File.separator
					+ imageName)) {

				if (url.contains(ImageManager.HTTP)
						|| url.contains(ImageManager.HTTPS)) {
					return loadBitmapFromInternet(url, imageName, cacheFilePath);

				} else {
					BitmapFactory.Options options = new BitmapFactory.Options();
					final InputStream is = mContext.getContentResolver()
							.openInputStream(Uri.parse(url));
					result = BitmapFactory.decodeStream(is, null, options);
					is.close();

				}

				result = ImageManager.getCorrectlyOrientedImage(mContext, uri,
						1, false, true);

			}

			if (url.contains(ImageManager.HTTP)
					|| url.contains(ImageManager.HTTPS)) {
				return ImageManager.compressImage(mContext, cacheFilePath
						+ File.separator + imageName);
			}

			result = ImageManager.getCorrectlyOrientedImage(mContext, uri, 1,
					false, true);
		} else {
			if (url.contains("storage")) {
				return ImageManager.getCorrectlyOrientedImage(mContext, url,
						5.0, false, true);
			}
			return getBitmapFromAsset(url);
		}
		return result;
	}

	private Bitmap loadBitmapFromInternet(String imageUrl, String imageName,
			String cacheFilePath) throws IOException {
		URL url = new URL(imageUrl);
		Bitmap result = super.getContent(url.openConnection());
		ImageManager.saveImageToFile(cacheFilePath, result, imageName);
		return ImageManager.compressImage(mContext, cacheFilePath
				+ File.separator + imageName);
	}

	private Bitmap getBitmapFromAsset(String strName) throws IOException {
		InputStream istr = mAssetManager.open(strName);
		Bitmap bitmap = BitmapFactory.decodeStream(istr);

		return bitmap;
	}

}
